// 视频流绑定与后台恢复播放

import { useEffect } from "react";

interface UseVideoStreamsBindingProps {
    streams: Map<string, MediaStream>;
    videoRefs: React.MutableRefObject<Map<string, HTMLVideoElement>>;
    onDefaultStreamPlaying: () => void;
}

export default function useVideoStreamsBinding({
    streams,
    videoRefs,
    onDefaultStreamPlaying,
}: UseVideoStreamsBindingProps) {
    // 将 stream 绑定到对应的 video 元素并处理默认流首次播放
    useEffect(() => {
        for (const [streamId, stream] of streams.entries()) {
            const videoEl = videoRefs.current.get(streamId);
            if (videoEl && !videoEl.srcObject) {
                videoEl.srcObject = stream;
                videoEl
                    .play()
                    .catch((e) => console.error(`播放流 ${streamId} 出错:`, e));

                if (streamId === "default") {
                    const onPlayingInit = () => {
                        onDefaultStreamPlaying();
                    };
                    videoEl.addEventListener("playing", onPlayingInit, { once: true });
                }
            }
        }
    }, [streams, videoRefs, onDefaultStreamPlaying]);

    // 防止后台标签页暂停/卡顿，强制恢复播放
    useEffect(() => {
        const keepPlaying = (e: Event) => {
            const video = e.target as HTMLVideoElement;
            if (video.paused) {
                video.play().catch((err) => console.error(`强制恢复播放失败:`, err));
            }
        };

        const videos = Array.from(videoRefs.current.values());
        for (const videoEl of videos) {
            videoEl.addEventListener("pause", keepPlaying);
            videoEl.addEventListener("stalled", keepPlaying);
        }

        return () => {
            const currentVideos = Array.from(videoRefs.current.values());
            for (const videoEl of currentVideos) {
                videoEl.removeEventListener("pause", keepPlaying);
                videoEl.removeEventListener("stalled", keepPlaying);
            }
        };
    }, [streams, videoRefs]);
} 